<?php

class run extends BaseAction {

	public function _default(){

		if(!isset($GLOBALS['argv'][2])) _exit(2);
		$name = $GLOBALS['argv'][2];
		
		self::build();
		self::matlab();
		
	}
	
	public function matlab(){
		if(!isset($GLOBALS['argv'][2])) _exit(2);
		$name = $GLOBALS['argv'][2];
		
		if(!file_exists("studies/$name.m")){
			echo verbose_message("== Compiled study $name.m not found, rebuilding");
			build();
		}
		
		echo verbose_message("== Launching study: $name");
		$cmdstr = "cd studies; matlab -nosplash -nodesktop -r $name.m -logfile ./doc/messages.log; cd ..";
		if(System("which matlab")==""){
			echo verbose_message("== Error: MATLAB not present on system");
			_exit(6);
		}
		System($cmdstr);
	}
	
	public function build(){
		if(!isset($GLOBALS['argv'][2])) _exit(2);
		$name = $GLOBALS['argv'][2];
		
		if(!file_exists("studies/$name.php")){
			echo verbose_message("== Error: study $name not found, exiting");
			_exit(5);
		}
		
		$GLOBALS['compile-stack'] = $GLOBALS['compile-views'] = array();
		$GLOBALS['compile-args'] = $GLOBALS['compile-scripts'] = array();

		echo verbose_message("== Parsing study: $name");
		require_once("studies/$name.php");
		
		$out = "function $name()\n\n";
		
		echo verbose_message("== Compiling scripts");
		foreach($GLOBALS['compile-scripts'] as $script){
			// build subfxns
			$out .= fetch_matlab($script);
		}
		
		echo verbose_message("== Compiling views");
		foreach($GLOBALS['compile-views'] as $view){
			// materialize views
			$out .= view_export($view);
		}
		
		echo verbose_message("== Building parse tree");
		foreach($GLOBALS['compile-stack'] as $part){
			// walk the stack constructed by the study script
			// to build the actual logic specified
			$out .= $part."\n";
		}
		
		$out .= "end";
		echo verbose_message("== Writing $name.m");
		if(file_put_contents("studies/$name.m",$out)){
			return true;
		} else {
			return false;
		}
	}
	
}